package com.example.reflectdemo.plugin;

import java.lang.reflect.Proxy;
import java.util.*;

public class HandlerMain {
    public static void main(String... args){
        // 使用SPI加载插件
        ServiceLoader<Handler> serviceLoader = ServiceLoader.load(Handler.class);
        List<Object> handlers = new ArrayList<>();
        Iterator<Handler> handlerIterator = serviceLoader.iterator();
        while (handlerIterator.hasNext()){
            Handler handler = handlerIterator.next();
            handlers.add(handler);
        }
        // 将加载的插件组装成InvocationHandler，以进行分发处理
        DispatcherInvocationHandler invocationHandler = new DispatcherInvocationHandler(handlers);
        // 生成代理对象
        Handler proxy = (Handler) Proxy.newProxyInstance(HandlerMain.class.getClassLoader(), new Class[]{Handler.class}, invocationHandler);
        // 调用handle方法
        proxy.handle("Test");
    }
}
